package com.buba.shirodemo.controller;

import com.buba.shirodemo.config.RetryLimitHashedCredentialsMatcher;
import com.buba.shirodemo.pojo.User;
import com.buba.shirodemo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
    @Autowired
    private UserService userService;
    @RequestMapping({"/","/index"})
    public String toIndex(Model moedel){
    moedel.addAttribute("msg","hello.shior");
    return "index";
    }
    @RequestMapping("user/add")
    public String add(){
        return "user/add";
    }
    @RequestMapping("user/upd")
    public String upd(){
        return "user/upd";
    }
    @RequestMapping("toLogin")
    public String toLogin(){
    return "login";
    }
    @RequestMapping("register")
    public String register(){
        return "register";
    }
    @RequestMapping("login")
    public String login(String username,String password,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //执行登录方法
        try {
            subject.login(token);
            return "index";
        }catch (UnknownAccountException e){
           model.addAttribute("msg","用户明错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码不存在");
            return "login";
        }
    }
    @Autowired
    private RetryLimitHashedCredentialsMatcher retryLimitHashedCredentialsMatcher;
    /**
     * 解除admin 用户的限制登录
     * 写死的 方便测试
     * @return
     */
    @RequestMapping("/unlockAccount")
    public String unlockAccount(Model model){
        model.addAttribute("msg","用户解锁成功");

        retryLimitHashedCredentialsMatcher.unlockAccount("12");

        return "login";
    }
    @RequestMapping("/notea")
    @ResponseBody
    public String unauther(){
        return "未经授权无法返回此页面";
    }
    @RequestMapping("register1")
    public String register(User user) {
        // 设置盐值
        Object salt = ByteSource.Util.bytes(user.getAccount());
        // 加密后的密码
        String newPassword = new SimpleHash("MD5", user.getPassword(), salt, 1000).toHex();
        user.setPassword(newPassword);
        if (userService.registerUser(user)) {
            return "redirect:/toLogin";
        }
        return "register";
    }
}
